import { createRouter, createWebHashHistory } from 'vue-router';
import router from '../router/index'
import Cookies from 'js-cookie'
import { getMenuListByRoleId } from '~/api/url'
import { post } from '~/api/http'
import { USER_TOKEN_KEY } from '~/store/keys'
import useUserStore from '~/store/modules/user'
import pinia from '~/store/pinia'
import layoutStore from '~/store'
import { isExternal, mapTwoLevelRouter, toHump } from '.'
const userStore = useUserStore(pinia)


function getRoutes() {
  return post({
    url: getMenuListByRoleId,
    data: {
      userId: userStore.userId,
      roleId: userStore.roleId,
    },
  }).then((res) => {
    return generatorRoutes(res.data)
  })
}


function generatorRoutes(res) {
  return res

}

const whiteRoutes = ['/login']
const whiteRoutes2 = ['/404']
const whiteRoutes3 = ['/']

function isTokenExpired() {
  const token = Cookies.get(USER_TOKEN_KEY)
  return !!token
}

const checkRouter = (dataRouter, toPath) => {
  let routechildren = false
  if (dataRouter && dataRouter.length > 0) {
    dataRouter.forEach(it => {
      const route = { ...it }
      if (toPath.includes(route.menuUrl)) {
        console.log(route.menuUrl);
        routechildren = true
        if (route.children && route.children.length > 0) {
          routechildren = false
          route.children.forEach(e => {
            if (toPath === e.menuUrl) {
              routechildren = true
            }
          })
        }

      }
    })
    return routechildren
  }
}
router.beforeEach(async (to) => {
  /*
  to 将要访问的路径
  from 才能改那个路径来的
  next() 放行
  next('/login') 强制跳转 会重新在跑一次路由
  next()

  */
  //当前是login页面不做变化
  // console.log(to, 'to.path');
  if (whiteRoutes.includes(to.path)) {
    return true
  }
  else if (whiteRoutes2.includes(to.path)) {
    return true
  }
  else if (whiteRoutes3.includes(to.path)) {
    return true
  }
  else {
    //没有token的话就去登录
    if (!isTokenExpired()) {
      return {
        path: '/login',
        query: { redirect: to.fullPath },
      }
    } else {
      //问题：这里没明白是做什么的
      const isEmptyRoute = layoutStore.isEmptyPermissionRoute()
      console.log(isEmptyRoute)
      if (isEmptyRoute) {
        // 加载路由
        const accessRoutes = []
        const tempRoutes = await getRoutes()
        accessRoutes.push(...tempRoutes)
        // accessRoutes.push({
        //   menuUrl: "/404",
        //   menuName: "404页面",
        //   iconPrefix: "iconfont",
        //   icon: "detail"
        // })
        // accessRoutes.push({
        //   menuUrl: "/",
        //   menuName: "首页",
        //   iconPrefix: "iconfont",
        //   icon: "detail"

        // })

        console.log(accessRoutes);
        //查询用户访问的地址是否在他的权限里

        let flag = checkRouter(accessRoutes, to.path)
        // console.log(flag, 'flag');
        if (flag == false) {
          return {
            path: '/404',
            query: { redirect: to.fullPath },
          }
        }
        else{
          return true
        }


      } else {
        return true
      }
    }
  }
})

// export default router;
// router.beforeEach(async (to) => {

//   const tempRoutes = await getRoutes()
//   console.log(tempRoutes,'tempRoutes')
// })

// export default router

// router.beforeEach(async (to, from, next) => {
//   if (to.path !== '/login' && !localStorage.get('token')) { // 判断是否登录  非`login`页面无`token`的话跳转到登录页面
//     next({ path: '/login' });
//   } else {
//     const stores = PublicStore() // pinia 状态管理
//     if (to.path !== '/login' && stores.power.length === 0) { // 判断是否获取过权限
//       let res = await stores.setPower() // 获取权限列表
//       if (res) {
//         getRoutesAuth(stores.power) // 根据权限列表挂载路由
//         next({ path: to.fullPath }) // 跳转页面
//       } else { // 获取权限失败返回到来源页面
//         next({ path: from.path, query: { hasPower: 1 } })
//       }
//     } else if (router.hasRoute(to.name)) { // 判断路由是否存在
//       next()
//     } else { // 路由不存在 返回原页面
//       next({ path: from.path, query: { hasPower: 1 } })
//     }
//   }
// });
// export default router;
